package io.xccit.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.xccit.entity.User;
import io.xccit.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author CH_ywx
 * @date 2023-06-05
 * @description
 */
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        User user = userMapper.selectOne(wrapper);
        List<GrantedAuthority> authRoles = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_admin");
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                new BCryptPasswordEncoder().encode(user.getPassword()),
                authRoles
        );
    }
}
